from app.aoduo_admin.models import AdminOperationLog
from app.account.models import UserInfo, UserLog, UserPassword
from django.http import JsonResponse
from django.contrib.auth.hashers import make_password
from rest_framework.views import APIView
from common.authCheck.adminAuth import check_admin_login, getAdminUser, adminAuthCheck
from common.dictInfo import model_to_dict
import json


class AdminUserControlView(APIView):
    """
    id1: ADD UserInfo
    id2: DELETE UserInfo
    id3: VIEW UserInfo
    id4: MOD UserInfo
    """

    EXCLUDE_USER_FIELDS = [
        'password', 'head_portrait'
    ]

    @check_admin_login
    def get(self, request, uid):
        """
        查看用户详细信息
        :param request:
        :param uid:
        :return:
        """
        admin_user = getAdminUser(request.session.get('admin'))
        authID = 3
        if adminAuthCheck(admin_user, authID):
            user = UserInfo.objects.filter(id=uid)
            if not user.exists():
                return JsonResponse({
                    'status': False,
                    'errMsg': '用户不存在'
                }, status=404)
            user = user[0]
            userLog = UserLog.objects.get(related_user=user)
            userDict = model_to_dict(user, exclude=self.EXCLUDE_USER_FIELDS)
            logDict = model_to_dict(userLog, exclude=['id', 'related_user'])
            AdminOperationLog.objects.create(
                related_admin=admin_user,
                related_auth_type_id=authID,
                other_message='view user ' + str(user.id) + ' ' + user.nickname
            )
            return JsonResponse({
                'status': True,
                'user': userDict,
                'log': logDict
            })
        else:
            return JsonResponse({
                'status': False,
                'errMsg': '你没有权限'
            }, status=401)

    @check_admin_login
    def put(self, request, uid):
        """
        修改用户信息
        :param request:
        :param uid:
        :return:
        """
        admin_user = getAdminUser(request.session.get('admin'))
        authID = 4
        if adminAuthCheck(admin_user, authID):
            user = UserInfo.objects.filter(id=uid)
            if not user.exists():
                return JsonResponse({
                    'status': False,
                    'errMsg': '用户不存在'
                }, status=404)
            user = user[0]
            jsonParams = json.loads((request.body).decode('utf-8'))
            if jsonParams.get('password') is not None:
                newPassword = make_password(jsonParams.get('password'))
                user.password.password = newPassword
            user.email = jsonParams.get('email', user.email)
            user.nickname = jsonParams.get('nickname', user.nickname)
            user.user_role = jsonParams.get('role', user.user_role)  # 用于认证用户身份，例如认证领队成员
            user.user_sex = jsonParams.get('sex', user.user_sex)
            user.realName = jsonParams.get('realName', user.realName)
            userDict = model_to_dict(user, exclude=self.EXCLUDE_USER_FIELDS)
            AdminOperationLog.objects.create(
                related_admin=admin_user,
                related_auth_type_id=authID,
                other_message='mod user ' + str(user.id) + ' ' + user.nickname
            )
            return JsonResponse({
                'status': True,
                'user': userDict
            })
        else:
            return JsonResponse({
                'status': False,
                'errMsg': '你没有权限'
            })

    @check_admin_login
    def delete(self, request, uid):
        """
        删除用户
        :param request:
        :param uid:
        :return:
        """
        admin_user = getAdminUser(request.session.get('admin'))
        authID = 2
        if adminAuthCheck(admin_user, authID):
            user = UserInfo.objects.filter(id=uid)
            if not user.exists():
                return JsonResponse({
                    'status': False,
                    'errMsg': '用户不存在'
                }, status=404)
            user = user[0]
            user.delete()
            AdminOperationLog.objects.create(
                related_admin=admin_user,
                related_auth_type_id=authID,
                other_message='delete user ' + str(user.id) + ' ' + user.nickname
            )
            return JsonResponse({
                'status': True,
                'uid': uid
            })
        else:
            return JsonResponse({
                'status': False,
                'errMsg': '你没有权限'
            })

    @check_admin_login
    def post(self, request):
        """
        新建用户
        :param request:
        :return:
        """
        admin_user = getAdminUser(request.session.get('admin'))
        authID = 1
        if adminAuthCheck(admin_user, authID):
            jsonParams = json.loads((request.body).decode('utf-8'))
            user = UserInfo.objects.filter(email__exact=jsonParams.get('email'))
            if user.exists():
                return JsonResponse({
                    'status': False,
                    'errMsg': '邮箱已经被注册'
                }, status=401)
            user = UserInfo.objects.filter(nickname__exact=jsonParams.get('nickname'))
            if user.exists():
                return JsonResponse({
                    'status': False,
                    'errMsg': '昵称已经被人抢先用啦'
                }, status=401)
            del user
            hash_password = make_password(jsonParams.get('password'))
            newPassword = UserPassword.objects.create(password=hash_password)
            newUser = UserInfo.objects.create(
                password=newPassword,
                email=jsonParams.get('email'),
                nickname=jsonParams.get('nickname')
            )
            UserLog.objects.create(related_user=newUser)
            AdminOperationLog.objects.create(
                related_admin=admin_user,
                related_auth_type_id=authID,
                other_message='ADD user ' + str(newUser.id) + ' ' + newUser.nickname
            )
            return JsonResponse({
                'status': True,
                'email': newUser.email,
                'id': newUser.id,
                'nickname': newUser.nickname
            })
        else:
            return JsonResponse({
                'status': False,
                'errMsg': '你没有权限'
            }, status=401)
